//
//  YHHomeMyMachineManagementListViewController.m
//  YHApp
//
//  Created by -- on 2021/7/19.
//

#import "HAAllMachineListVC.h"
#import "HAMachinePullDownRecordVC.h"
#import "HAMachinePullDownVC.h"
#import "HAAllMachineListCell.h"
#import "HAAllMachineListMo.h"
#import "HAMachineDVC.h"
#import "HAMyMachineScreenPopView.h"
#import "HAPolicyListMo.h"

@interface HAAllMachineListVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
/***/
@property (nonatomic, strong) UITextField *seachField;
/***/
@property (nonatomic, strong) NSString *state;
/***/
@property (nonatomic, strong) NSString *keyword;
/***/
@property (nonatomic, strong) NSString *isTeam;

/***/
@property (nonatomic, strong) NSMutableArray *canalItemMoArr;
/***/
@property (nonatomic, strong) NSMutableArray *policyLists;

/***/
@property (nonatomic, strong) NSMutableArray *numLabelArray;
/***/
@property (nonatomic, strong) NSMutableArray *titLabelArray;

/***/
@property (nonatomic, strong) UIView *bottonV;
/***/
@property (nonatomic, strong) NSString *source_id;


@end

@implementation HAAllMachineListVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseTLabel.text = @"所有机具";
    
    self.source_id = @"all";
    self.isTeam = @"";
    
    [self setupUI];
    
    MJRefreshGifHeader *mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_header = mj_header;
    
    MJRefreshBackGifFooter *mj_footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(laodMoreData)];
    self.tableView.mj_footer = mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
    [self loadProductItems];
    [self loadPolicyItems];
    
    // Do any additional setup after loading the view.
}

-(void)dealloc {
    for (HACanalItemMo *mo in [HASingle single].canalItemArray) {
        mo.isSel = NO;
    }
}

-(void)setupUI {
    
    UIView *seachBgView = [UIView ha_createView];
    seachBgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:seachBgView];
    [seachBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.baseNavView.mas_bottom).offset(0.6);
        make.left.right.mas_equalTo(0);
        make.height.mas_offset(44);
    }];
    
    UIButton *moreBtn = [[UIButton alloc]init];
    [moreBtn setTitle:@"筛选" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:moreBtn];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];
    
    
    UIButton *seachBtn = [[UIButton alloc]init];
    [seachBtn setImage:[UIImage xl_cuttingImageWith:[UIImage imageNamed:@"ha_searchIcon"] toSize:CGSizeMake(22, 22)] forState:UIControlStateNormal];
    [seachBtn addTarget:self action:@selector(seachBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [seachBgView addSubview:seachBtn];
    [seachBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(moreBtn.mas_left).offset(-5);
        make.centerY.mas_equalTo(0);
        make.width.mas_offset(32);
        make.height.mas_offset(32);
    }];
    
    UITextField *seachField = [[UITextField alloc]init];
    self.seachField = seachField;
    seachField.delegate = self;
    seachField.placeholder = @"请输入机具编号";
    seachField.font = [UIFont systemFontOfSize:18];
    seachField.returnKeyType = UIReturnKeySearch;
    [seachBgView addSubview:seachField];
    [seachField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.equalTo(seachBtn.mas_left).offset(-15);
        make.centerY.mas_equalTo(0);
        make.height.equalTo(@32);
    }];
    
    ///统计
    CGFloat sp = 6;
    CGFloat modViewX = 12;
    CGFloat modViewY = app_topH + 44 + 54;
    CGFloat modViewW = (kUIScreen_w-24-sp-sp)/3;
    CGFloat modViewH = 60;
    NSArray *titles = @[@"未绑定",@"已绑定",@"伪激活",@"已激活",@"未达标",@"已达标"];
    
    
    [self.titLabelArray removeAllObjects];
    [self.numLabelArray removeAllObjects];
    
    for (int i = 0; i < titles.count; i ++) {
        NSString *title = titles[i];
        UIColor *bgColor;
        if (i == 0 || i == 3) {
            bgColor = [UIColor colorWithHexString:@"#4876F1"];
        }
        if (i == 1 || i == 4) {
            bgColor = [UIColor colorWithHexString:@"#6AE176"];
        }
        if (i == 2 || i == 5) {
            bgColor = [UIColor colorWithHexString:@"#E95D5E"];
        }
        if (i == 1) {
            modViewX = 12 + modViewW + sp;
        }
        if (i == 2) {
            modViewX = 12 + modViewW + sp + modViewW + sp;
        }
        if (i == 3) {
            modViewX = 12;
            modViewY = app_topH + 44 + 54 + 60 + sp;
        }
        if (i == 4) {
            modViewX = 12 + modViewW + sp;
            modViewY = app_topH + 44 + 54 + 60 + sp;
        }
        if (i == 5) {
            modViewX = 12 + modViewW + sp + modViewW + sp;
            modViewY = app_topH + 44 + 54 + 60 + sp;
        }
        UIView *modView = [self getModView:i title:title bgColor:bgColor];
        modView.frame = CGRectMake(modViewX, modViewY, modViewW, modViewH);
        [self.view addSubview:modView];
    }
    
    self.bottonV = [UIView ha_createView];
    [self.view addSubview:self.bottonV];
    [self.bottonV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.height.mas_offset(54);
    }];
    
    UIButton *leftBtn = [[UIButton alloc]init];
    [leftBtn setTitle:@"划拔/接收记录" forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor colorWithHexString:@"#5f67fc"] forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bottonV addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_offset(kUIScreen_w*0.5);
        make.height.mas_offset(54);
    }];
    
    UIButton *rightBtn = [[UIButton alloc]init];
    [rightBtn setTitle:@"划拔" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithHexString:@"@ffffff"] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.backgroundColor = [UIColor colorWithHexString:@"#191919"];
    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bottonV addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_offset(kUIScreen_w*0.5);
        make.height.mas_offset(54);
    }];
    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(app_topH+44+54+60+sp+60);
        make.bottom.mas_equalTo(self.bottonV.mas_top);
    }];
}

-(UIView *)getModView:(NSInteger)type title:(NSString *)title bgColor:(UIColor *)bgColor {
    UIView *view = [UIView ha_createView];
    view.backgroundColor = bgColor;
    
    UILabel *titLabel = [UILabel ha_NLabelWithFont:12 textColor:@"#ffffff" text:title alignment:1];
    [view addSubview:titLabel];
    [titLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(14);
        make.height.mas_offset(14);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    UILabel *numLabel = [UILabel ha_NLabelWithFont:14 textColor:@"#ffffff" text:@"0" alignment:1];
    [view addSubview:numLabel];
    [numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(-14);
        make.height.mas_offset(14);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];
    
    [self.titLabelArray addObject:titLabel];
    [self.numLabelArray addObject:numLabel];
    return view;
}

-(void)leftBtnClick {
    HAMachinePullDownRecordVC *vc = [[HAMachinePullDownRecordVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)rightBtnClick {
    HAMachinePullDownVC *vc = [[HAMachinePullDownVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HAAllMachineListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YHHomeMyMachineManagementListSubCellID"];
    if (!cell) {
        cell = [[HAAllMachineListCell alloc]initWithStyle:0 reuseIdentifier:@"YHHomeMyMachineManagementListSubCellID"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HAAllMachineListMo *model = self.dataArray[indexPath.row];
    HAMachineDVC *vc = [[HAMachineDVC alloc]init];
    vc.sn = model.sn;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)seachBtnClick {
    if ([NSString isEmptyString:self.seachField.text]) {
        [MBProgressHUD showError:@"请输入机具编号"];
        return;
    }
    
    self.keyword = self.seachField.text;
    
    [self.tableView.mj_header beginRefreshing];
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self.view endEditing:YES];
    
    if (textField == self.seachField) {
        if ([NSString isEmptyString:self.seachField.text]) {
            [MBProgressHUD showError:@"请输入机具编号"];
            return NO;
        }
        
        self.keyword = textField.text;
        
        [self.tableView.mj_header beginRefreshing];
    }
    
    return YES;
}

-(void)moreBtnClick{
    WS(weakSelf)
    HAMyMachineScreenPopView *menu = [[HAMyMachineScreenPopView alloc]init];
    menu.canalItemMoArr = self.canalItemMoArr;
    menu.policyLists = self.policyLists;
    menu.isTeam = self.isTeam;
    menu.keyword = self.keyword;
    menu.state = self.state;
    [menu loadViews];
    [menu show];
    menu.HAMyMachineScreenPopViewBlock = ^(NSString * _Nonnull searchText, NSString * _Nonnull state, NSString * _Nonnull isTeam) {
        weakSelf.state = state;
        weakSelf.isTeam = isTeam;
        weakSelf.keyword = searchText;
        weakSelf.seachField.text = searchText;
        [weakSelf.tableView.mj_header beginRefreshing];
    };
}


-(void)loadNewData {
    
    NSString *product_id = @"";
    NSString *policy_id = @"";
    for (HACanalItemMo *mo in self.canalItemMoArr) {
        if (mo.isSel) {
            product_id = mo.value;
            break;
        }
    }
    for (HAPolicyListMo *mo in self.policyLists) {
        if (mo.isSel) {
            policy_id = mo.policy_id;
            break;
        }
    }
    NSString *source_id = @"";
    for (HACanalItemMo *mo in [HASingle single].canalItemArray) {
        if (mo.isSel == YES) {
            source_id = mo.value;
            break;
        }
    }
    self.source_id = source_id;
    if ([NSString isEmptyString:self.source_id]) {
        self.source_id = @"all";
    }
    
    NSDictionary *dict = @{
        @"pageSize":@"10",
        @"page":@"1",
        @"source_id":self.source_id?:@"",
        @"state":self.state?:@"",
        @"keyword":self.keyword?:@"",
        @"isTeam":self.isTeam?:@"",
        @"product_id":product_id,
        @"policy_id":policy_id,
        
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"sns/lists.html"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_header endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                [self.dataArray removeAllObjects];
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAAllMachineListMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
                
                if ([[dataModel.data allKeys]containsObject:@"itemall"]) {
                    NSArray *items = dataModel.data[@"itemall"];
                    for (int i = 0; i < items.count; i ++) {
                        NSDictionary *dic = items[i];
                        if (self.titLabelArray.count > i && self.numLabelArray.count > i) {
                            UILabel *titLabel = self.titLabelArray[i];
                            UILabel *numLabel = self.numLabelArray[i];
                            titLabel.text = dic[@"label"];
                            numLabel.text = [NSString stringWithFormat:@"%@",dic[@"number"]];
                        }
                    }
                }
                
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
            
        }
    }];
    
}

-(void)laodMoreData {
    
    NSString *product_id = @"";
    NSString *policy_id = @"";
    for (HACanalItemMo *mo in self.canalItemMoArr) {
        if (mo.isSel) {
            product_id = mo.value;
            break;
        }
    }
    for (HAPolicyListMo *mo in self.policyLists) {
        if (mo.isSel) {
            policy_id = mo.policy_id;
            break;
        }
    }
    NSString *source_id = @"";
    for (HACanalItemMo *mo in [HASingle single].canalItemArray) {
        if (mo.isSel == YES) {
            source_id = mo.value;
            break;
        }
    }
    self.source_id = source_id;
    if ([NSString isEmptyString:self.source_id]) {
        self.source_id = @"all";
    }
    
    NSInteger count = ceilf(self.dataArray.count*0.1)+1;
    NSString *pageNo = [NSString stringWithFormat:@"%ld",(long)count];
    
    NSDictionary *dict = @{
        @"pageSize":@"10",
        @"page":pageNo,
        @"source_id":self.source_id?:@"",
        @"state":self.state?:@"",
        @"keyword":self.keyword?:@"",
        @"isTeam":self.isTeam?:@"",
        @"product_id":product_id,
        @"policy_id":policy_id,
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"sns/lists.html"];
    request1.requestMethod = SYRequestMethodPOST;
    request1.parms = dict;
    
    [self.tableView.mj_footer beginRefreshing];
    
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            
            [self.tableView.mj_footer endRefreshing];
            
            if (dataModel.err) {
                [MBProgressHUD showError:@"网络错误"];
                return;
            }
            if (dataModel.code == 1) {
                if ([[dataModel.data allKeys]containsObject:@"data"]) {
                    NSArray *arr = [HAAllMachineListMo mj_objectArrayWithKeyValuesArray:[dataModel.data valueForKey:@"data"]];
                    [self.dataArray addObjectsFromArray:arr];
                }
            }else{
                [MBProgressHUD showError:dataModel.msg];
            }
            
            [self.tableView reloadData];
        }
    }];
    
}

-(void)loadProductItems {
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = [NSString stringWithFormat:@"product/items"];
    request1.requestMethod = SYRequestMethodPOST;
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            if (dataModel.code == 1) {
                [self.canalItemMoArr removeAllObjects];
                NSArray *array = [HACanalItemMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                [self.canalItemMoArr addObjectsFromArray:array];
            }
        }
    }];
}

-(void)loadPolicyItems {
    NSDictionary *dict = @{
        @"canal" : @"",
    };
    SYRequest *request1 = [[SYRequest alloc]init];
    request1.requestUrl = @"v1/policy/lists";
    request1.requestMethod = SYRequestMethodGET;
    request1.parms = dict;
    [[SYNetworking shareSingle] hgj_asynRequestWithArray:@[request1] responseBlock:^(SYDataModel *dataModel) {
        if (dataModel.request == request1) {
            if (dataModel.code == 1) {
                [self.policyLists removeAllObjects];
                NSArray *array = [HAPolicyListMo mj_objectArrayWithKeyValuesArray:dataModel.data];
                [self.policyLists addObjectsFromArray:array];
            }
        }
    }];
    
}

- (NSMutableArray *)canalItemMoArr
{
    if (!_canalItemMoArr) {
        _canalItemMoArr = [NSMutableArray array];
    }
    return _canalItemMoArr;
}


- (NSMutableArray *)numLabelArray
{
    if (!_numLabelArray) {
        _numLabelArray = [NSMutableArray array];
    }
    return _numLabelArray;
}

- (NSMutableArray *)titLabelArray
{
    if (!_titLabelArray) {
        _titLabelArray = [NSMutableArray array];
    }
    return _titLabelArray;
}

- (NSMutableArray *)policyLists
{
    if (!_policyLists) {
        _policyLists = [NSMutableArray array];
    }
    return _policyLists;
}


- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        // 去掉滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.backgroundColor = [UIColor khaBGColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



#pragma mark - 无数据处理 DZNEmptyDataSetSource DZNEmptyDataSetDelegate

//设置title
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无数据~";
    NSDictionary *attributes = @{
        NSFontAttributeName:[UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#999999"]
    };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

//设置image
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"hl_nodata"];
}



@end

